/*
 * BeanUtils.java
 *
 * Created on 12 de Outubro de 2007, 12:13
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package br.uff.javaavancado.util;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

/**
 *
 * @author thiago
 */
public class BeanUtils {
    
    protected static ClassLoader getCurrentClassLoader(Object defaultObject){
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if(loader == null){
            loader = defaultObject.getClass().getClassLoader();
        }
        return loader;
    }
    
    public static String getMessageResourceString(
            String bundleName,
            String key,
            Object params[],
            Locale locale){
        
        String text = null;
        
        ResourceBundle bundle =
                ResourceBundle.getBundle(bundleName, locale,
                getCurrentClassLoader(params));
        
        try{
            text = bundle.getString(key);
        } catch(MissingResourceException e){
            text = "?? chave " + key + " não encontrada ??";
        }
        
        if(params != null){
            MessageFormat mf = new MessageFormat(text, locale);
            text = mf.format(params, new StringBuffer(), null).toString();
        }
        
        return text;
    }
    
    public static String preparaStringBuscaIlike(String str){
        String temp = "%";
        StringTokenizer st = new StringTokenizer(str," ");
        while (st.hasMoreTokens()){
            temp += st.nextToken()+ "%";
        }
        return temp;
    }
    
    public static List<SelectItem> getListaString(String nome){
        String linha = getMessageResourceString(FacesContext.getCurrentInstance().getApplication()
        .getMessageBundle(), nome, null, FacesContext.getCurrentInstance().getViewRoot().getLocale());
        
        String[] tokens = linha.split("#");
        ArrayList<SelectItem> lista = new ArrayList<SelectItem>(tokens.length);
        
        for (String elem : tokens) {
            lista.add(new SelectItem(elem, elem));
        }
        
        return lista;
    }
}

